<template>
  <el-dialog
    title="用户注册"
    class="my_register"
    :visible.sync="dialogFormVisible"
    center
    width="600px"
    @closed="closedLogic"
  >
    <!-- 表单 -->
    <el-form :model="form" :rules="rules" ref="regForm">
      <el-form-item
        label="头像"
        :label-width="formLabelWidth"
        required
        prop="avatar"
      >
        <el-upload
          class="avatar-uploader"
          :action="uploadUrl"
          name="image"
          :show-file-list="false"
          :on-success="handleAvatarSuccess"
          :before-upload="beforeAvatarUpload"
        >
          <img v-if="imageUrl" :src="imageUrl" class="avatar" />
          <i v-else class="el-icon-plus avatar-uploader-icon"></i>
        </el-upload>
      </el-form-item>
      <!-- 用户名 -->
      <el-form-item
        label="用户名"
        :label-width="formLabelWidth"
        prop="username"
      >
        <el-input v-model="form.username" autocomplete="off"></el-input>
      </el-form-item>
      <!-- 密码 -->
      <el-form-item
        label="密码"
        :label-width="formLabelWidth"
        prop="password"
        required
      >
        <el-input v-model="form.password" autocomplete="off"></el-input>
      </el-form-item>
      <!-- 邮箱地址 -->
      <el-form-item
        label="邮箱"
        :label-width="formLabelWidth"
        prop="email"
        required
      >
        <el-input v-model="form.email" autocomplete="off"></el-input>
      </el-form-item>
      <!-- 手机号码 -->
      <el-form-item
        label="手机"
        :label-width="formLabelWidth"
        prop="phone"
        required
      >
        <el-input v-model="form.phone" autocomplete="off"></el-input>
      </el-form-item>
      <!-- 图形码 -->
      <el-form-item label="图形码" :label-width="formLabelWidth" prop="code">
        <el-row>
          <el-col :span="16">
            <el-input v-model="form.code" autocomplete="off"></el-input>
          </el-col>
          <el-col :span="7" :offset="1"
            ><img :src="codeUrl" class="code-img" @click="changeImg" alt=""
          /></el-col>
        </el-row>
      </el-form-item>
      <!-- 验证码 -->
      <el-form-item label="验证码" :label-width="formLabelWidth" prop="rcode">
        <el-row>
          <el-col :span="16">
            <el-input v-model="form.rcode" autocomplete="off"></el-input>
          </el-col>
          <el-col :span="7" :offset="1"
            ><el-button :disabled="this.count !== 0" @click="getCode">{{
              codeMsg
            }}</el-button></el-col
          >
        </el-row>
      </el-form-item>
    </el-form>
    <div slot="footer" class="dialog-footer">
      <el-button type="primary" @click="submitForm">确 定</el-button>
      <el-button @click="dialogFormVisible = false">取 消</el-button>
    </div>
  </el-dialog>
</template>

<script>
import { getSMSCode, register } from '../../api/register'
export default {
  data () {
    return {
      imageUrl: '',
      dialogFormVisible: false,
      form: {
        username: '',
        password: '',
        email: '',
        phone: '',
        msmCode: '',
        avatar: '',
        rcode: ''
      },
      // 校验规则
      rules: {
        username: [
          {
            required: true,
            message: '用户名不能为空',
            trigger: 'blur'
          },
          {
            min: 2,
            max: 11,
            message: '用户名长度为 2 到 11',
            trigger: 'blur'
          }
        ],
        phone: [
          {
            required: true,
            message: '手机号不能为空',
            trigger: 'blur'
          },
          {
            pattern: /^(0|86|17951)?(13[0-9]|15[012356789]|166|17[3678]|18[0-9]|14[57])[0-9]{8}$/,
            message: '手机号格式有误',
            trigger: 'blur'
          }
        ],
        email: [
          {
            required: true,
            message: '邮箱不能为空',
            trigger: 'blur'
          },
          {
            type: 'email',
            message: '邮箱格式有误',
            trigger: 'blur'
          }
        ],
        avatar: [
          {
            required: true,
            message: '头像不能为空',
            trigger: 'blur'
          }
        ],
        password: [
          {
            required: true,
            message: '密码不能为空',
            trigger: 'blur'
          },
          {
            min: 6,
            max: 18,
            message: '密码的长度为 6 到 18',
            trigger: 'blur'
          }
        ],
        rcode: [
          {
            required: true,
            message: '短信验证码不能为空',
            trigger: 'blur'
          },
          {
            min: 4,
            max: 4,
            message: '短信验证码的长度为 4',
            trigger: 'blur'
          }
        ],
        code: [
          {
            required: true,
            message: '验证码不能为空',
            trigger: 'blur'
          },
          {
            min: 4,
            max: 4,
            message: '验证码的长度为 4',
            trigger: 'blur'
          }
        ]
      },
      // 表单右侧距离
      formLabelWidth: '72px',
      // 注册验证码图片地址
      codeUrl: process.env.VUE_APP_BaseURL + '/captcha?type=sendsms',
      // 头像上传基地址
      uploadUrl: process.env.VUE_APP_BaseURL + '/uploads',
      // 验证码按钮提示信息
      codeMsg: '点击获取验证码',
      // 倒计时
      count: 0
    }
  },
  methods: {
    // 关闭清空表单
    closedLogic () {
      this.$refs.regForm.resetFields()
      this.imageUrl = ''
    },
    // 点击提交表单
    submitForm () {
      // validate方法传入一个回调函数,该回调函数参数为一个booler值,当表单全部校验成功这个booler值为true,否则为false
      this.$refs.regForm.validate(valid => {
        if (valid) {
          // this.$message.success('校验成功');
          // 获取表单数据
          const { username, phone, email, avatar, password, rcode } = this.form
          // console.log(username, phone, email, avatar, password, rcode)
          // 根据数据发起请求
          register({ username, phone, email, avatar, password, rcode }).then(
            res => {
              console.log(res)
              this.$message.success('注册成功')
              // 关闭窗口
              this.dialogFormVisible = false
            }
          )
        } else {
          this.$message.error('信息错误')
          return false
        }
      })
    },

    // 验证码信息
    getCode () {
      // 对表单中的phone和code字段校验
      let flag = 0
      this.$refs.regForm.validateField(['phone', 'code'], errormsg => {
        if (!errormsg) {
          flag++
        }
      })
      if (flag !== 2) {
        this.$message.error('请填写手机号和验证码字段')
        return
      }
      if (this.count === 0) {
        // 设置初始时间
        this.count = 3
        // 设置按钮文本
        this.codeMsg = `还剩${this.count}秒`
        // 开启倒计时
        const timeId = setInterval(() => {
          this.count--
          if (this.count === 0) {
            clearInterval(timeId)
            this.codeMsg = '点击获取验证码'
            return
          }
          this.codeMsg = `还剩${this.count}秒`
        }, 1000)
      }
      // 获取手机好和验证码
      const { phone, code } = this.form
      // 利用导入的api模块发起请求
      getSMSCode({
        code,
        phone
      })
        .then(res => {
          this.$message.success('验证码:' + res.data.data.captcha)
        })
        .catch(err => {
          console.log(err)
        })
    },
    // 刷新验证码图片
    changeImg () {
      // 利用时间戳重新给codeUrl赋值
      this.codeUrl =
        process.env.VUE_APP_BaseURL + '/captcha?type=sendsms&t=' + Date.now()
      // 利用随机数重新给codeUrl赋值
      // this.codeUrl =
      //   process.env.VUE_APP_BaseURL +
      //   '/captcha?type=sendsms?&t=' +
      //   Math.random()
    },
    // 图片上传后创建图片路径并保存地址
    handleAvatarSuccess (res, file) {
      this.imageUrl = URL.createObjectURL(file.raw)
      // 保存头像地址,并预览
      this.form.avatar = res.data.file_path
      // 清空错误提示
      this.$refs.regForm.clearValidate('avatar')
    },
    // 图片上传前的检测
    beforeAvatarUpload (file) {
      const isJPG = file.type === 'image/jpeg'
      const isLt2M = file.size / 1024 / 1024 < 2
      if (!isJPG) {
        this.$message.error('上传头像图片只能是 JPG 格式!')
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!')
      }
      return isJPG && isLt2M
    }
  }
}
</script>

<style lang="less">
.my_register {
  .el-dialog__header {
    background: linear-gradient(to right, #01c6fa 28%, #1493fa 96%);
    color: white;
  }
  .avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }

  .avatar-uploader .el-upload:hover {
    border-color: #409eff;
  }

  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
  }

  .avatar {
    width: 178px;
    height: 178px;
    display: block;
  }
  .el-form-item__content {
    text-align: center;
  }

  .code-img {
    display: block;
    width: 100%;
  }
  .el-dialog--center .el-dialog__body {
    padding-left: 15px;
  }
}
</style>
